package com.bum.api.core.util.render;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class RenderUtil {
	private static final String	URL_REGEX		= "(?:(?:ht|f)tp(?:s?)://)(?:(?:[-\\w]+\\.)+(?:[-\\w]+))(?::[\\d]{1,5})?(?:(?:(?:/(?:[-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|/)+|\\?|#)?(?:(\\S)*)";
	private static final String	URL_HTML		= "<a href=\"$0\" class=\"http\" target=\"_blank\" rel=\"http\">$0</a>";
	private static final String	YOUTUBE_HTML	= "<a href=\"{0}\" class=\"youtube youtube-{1}\" rel=\"http\" code=\"{1}\">{0}</a>";
	static Pattern				urlPattern		= Pattern.compile(URL_REGEX);

	public static String renderHttp(String html) {
		Matcher matcher = urlPattern.matcher(html);
		boolean result = matcher.find();
		if (result) {
			StringBuffer sb = new StringBuffer();
			do {
				String url = matcher.group(0);
				if (url.startsWith("http://youtu.be/")) {
					String code = url.substring("http://youtu.be/".length());
					if (code.indexOf("?") > -1) {
						code = code.substring(0, code.indexOf("?"));
					}
					if (StringUtils.isNotBlank(code)) {
						url = MessageFormat.format(YOUTUBE_HTML, url, code);
						matcher.appendReplacement(sb, url);
					} else {
						matcher.appendReplacement(sb, URL_HTML);
					}
				} else {
					matcher.appendReplacement(sb, URL_HTML);
				}
				result = matcher.find();
			} while (result);
			matcher.appendTail(sb);
			return sb.toString();
		}
		return html;
	}
}
